import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mall/constant/app_colors.dart';
import 'package:mall/constant/app_strings.dart';
import 'package:mall/constant/text_style.dart';
import 'package:mall/modules/model/goods_detail_entity.dart';
import 'package:mall/modules/service/cart_service.dart';
import 'package:mall/modules/service/goods_service.dart';
import 'package:mall/modules/service/user_service.dart';
import 'package:mall/router/navigator_util.dart';
import 'package:mall/ui/page/goods/widgets/goods_price_widget.dart';
import 'package:mall/ui/widgets/cart_number.dart';
import 'package:mall/utils/hud/hud_util.dart';
import 'package:mall/utils/image_component/image_component.dart';

class GoodsDetailSelectGoodsWidget extends StatefulWidget {
  const GoodsDetailSelectGoodsWidget({super.key, required this.model, required this.showType});
  final GoodsDetailEntity model;
  final int showType;
  @override
  State<GoodsDetailSelectGoodsWidget> createState() => _GoodsDetailSelectGoodsWidgetState();
}

class _GoodsDetailSelectGoodsWidgetState extends State<GoodsDetailSelectGoodsWidget> {
  int _number = 1;
  //选中的规格列表
  final RxList<GoodsDetailSpecificationlistValuelist> specificationList = <GoodsDetailSpecificationlistValuelist>[].obs;
  //选中的产品
  late final Rx<GoodsDetailProductlist> productSelect =
      widget.model.productList?.first.obs ?? GoodsDetailProductlist().obs;

  @override
  void initState() {
    //默认选中
    widget.model.specificationList?.forEach((element) {
      final a = element.valueList?.first;
      if (a != null) {
        specificationList.add(a);
      }
    });

    //监听当前选择的规格
    ever(specificationList, (value) {
      //如果当前选择的规格,被某个产品包含,那么该产品就是被默认选中的
      widget.model.productList?.forEach((product) {
        final specifications = product.specifications;
        if (specifications == null || specifications.isEmpty) {
          return;
        }
        bool isCheck = true;
        specificationList.forEach((specification) {
          if (!specifications.contains(specification.value)) {
            isCheck = false;
          }
        });

        if (isCheck) {
          productSelect.value = product;
        }
      });
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Obx(() => Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  //图片
                  ImageComponent(
                    productSelect.value.url,
                    borderRadius: BorderRadius.circular(8),
                    size: 100,
                  ),
                  SizedBox(width: 10),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      //价格
                      GoodsPriceWidget(
                        price: productSelect.value.price,
                        priceColor: AppColors.C_EC2010,
                      ),
                      //选择的规格
                      Text(
                        AppStrings.ALREAD_SELECTED + (productSelect.value.specifications?.join(',') ?? ""),
                        style: TextStyle(fontSize: 12, color: Color(0xffb8b8b8)),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ],
              )),
          SizedBox(height: 20),
          //规格
          // Text(AppStrings.SPECIFICATIONS, style: FMTextStyle.color_333333_size_42),
          // SizedBox(height: 10),
          // Wrap(
          //     spacing: 10,
          //     children: _specificationsWidget(model.specificationList ?? [], specificationId.value)),
          _specificationsWidget(widget.model.specificationList ?? []),
          Spacer(),
          //数量
          Row(
            children: [
              Text(AppStrings.NUMBER, style: FMTextStyle.color_222222_size_13),
              Expanded(
                child: Container(
                  // margin: EdgeInsets.all(15),
                  alignment: Alignment.centerRight,
                  child: CartNumberView(1, (number) {
                    _number = number;
                    print(number);
                  }),
                ),
              ),
            ],
          ),
          // SizedBox(height: 50),

          SizedBox(height: 20),
          //立即购买
          Container(
            height: 40,
            width: double.infinity,
            child: ElevatedButton(
              style: ButtonStyle(
                backgroundColor: WidgetStateProperty.all(
                  widget.showType == 1 ? AppColors.C_FF5722 : AppColors.C_FFB24E,
                ),
                shape: WidgetStateProperty.all(
                  RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(20)),
                  ),
                ),
                elevation: WidgetStateProperty.all(0), // 如果不需要阴影，可以设置为 0
              ),
              onPressed: () => widget.showType == 1 ? _addCart(widget.model) : _buy(widget.model),
              child: Text(
                widget.showType == 1 ? AppStrings.ADD_CART : AppStrings.BUY,
                style: FMTextStyle.color_ffffff_size_13,
              ),
            ),
          ),
          SizedBox(height: 15),
        ],
      ),
    );
  }

  //规格
  Widget _specificationsWidget(List<GoodsDetailSpecificationlist> specifications) {
    List<Widget> specificationsWidget = [];

    for (int i = 0; i < specifications.length; i++) {
      final element = specifications[i];
      final valueList = element.valueList;
      if (valueList == null || valueList.isEmpty) {
        continue;
      }
      specificationsWidget.add(
        Container(
          padding: EdgeInsets.only(top: 10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '${element.name}',
                style: TextStyle(fontSize: 13, color: AppColors.C_222222),
              ),
              // SizedBox(height: 5),
              Obx(() => Wrap(
                    spacing: 10,
                    children: valueList.map((e) {
                      final select = specificationList[i].id == e.id;

                      return ChoiceChip(
                        showCheckmark: false,
                        label: Text(
                          e.value ?? "",
                          style: TextStyle(fontSize: 12, color: select ? AppColors.C_FD2C55 : AppColors.C_222222),
                        ),
                        selected: select,
                        selectedColor: Color(0xffffeceb),
                        disabledColor: Color(0xfff2f2f2),
                        backgroundColor: Color(0xfff2f2f2),
                        onSelected: (value) {
                          //选中后,将选中的规格赋值
                          specificationList[i] = e;
                        },
                      );
                    }).toList(),
                  )),
            ],
          ),
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: specificationsWidget,
    );
  }

  _addCart(GoodsDetailEntity model) async {
    final islogin = await UserService.isLogin();
    if (!islogin) {
      NavigatorUtil.goLogin();
      return;
    }
    ;

    CartService.addCart(model.info?.id ?? 0, productSelect.value.id ?? 0, _number).then((response) {
      HUDUtil.toast('添加购物车成功');
      Get.back();
    });
  }

  _buy(GoodsDetailEntity model) async {
    final islogin = await UserService.isLogin();
    if (!islogin) {
      NavigatorUtil.goLogin();
      return;
    }
    ;

    GoodsService.buy(
      goodsId: model.info?.id ?? 0,
      productId: productSelect.value.id ?? 0,
      number: _number,
    ).then((response) {
      Get.back();
      NavigatorUtil.goFillInOrder(response);
    });
  }
}
